package com.ssm.service.Impl;

import com.ssm.security.JwtTokenUtil;
import com.ssm.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl implements AuthService {

    private AuthenticationManager authenticationManager;
    private UserDetailsService userDetailsService;
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    public AuthServiceImpl(
            AuthenticationManager authenticationManager,
            UserDetailsService userDetailsService,
            JwtTokenUtil jwtTokenUtil) {
        this.authenticationManager = authenticationManager;
        this.userDetailsService = userDetailsService;
        this.jwtTokenUtil = jwtTokenUtil;
    }



    @Override
    public String login(String username, String password) {
        //将用户名、密码封装成一个token
        UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
        // Perform the com.ssm.security 将token传给AuthenticationManager进行身份认证 ,认证完毕，返回一个认证后的身份
        final Authentication authentication = authenticationManager.authenticate(upToken);
        //认证后，存储到SecurityContext里
        SecurityContextHolder.getContext().setAuthentication(authentication);

        // Reload password post-com.ssm.security so we can generate token
        final UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        final String token = jwtTokenUtil.generateToken(userDetails);
        return token;
    }


}

/*通常情况下，我们的系统都是这样的：

1、用户输入用户名、密码登录

2、系统对用户名、密码进行验证

3、获取用户上下文信息（角色列表等等）

4、获取相关操作权限


对于上面说的前三条，用Spring Security来处理，就是：

1、用户名、密码组合生成一个Authentication对象（也就是UsernamePasswordAuthenticationToken对象）。

2、生成的这个token对象会传递给一个AuthenticationManager对象用于验证。

3、当成功认证后，AuthenticationManager返回一个Authentication对象。

4、接下来，就可以存入

SecurityContextHodler.getContext().setAuthentication(…)。


从SecurityContext读取认证的身份：

System.out.println(SecurityContextHolder.getContext().getAuthentication())*/
